package cn.iocoder.an.module.business.dal.mysql.repairtask;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import cn.iocoder.an.framework.common.pojo.PageResult;
import cn.iocoder.an.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.an.framework.mybatis.core.mapper.BaseMapperX;
import cn.iocoder.an.module.business.dal.dataobject.repairtask.RepairTaskDO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.ibatis.annotations.Mapper;
import cn.iocoder.an.module.business.controller.admin.repairtask.vo.*;

/**
 * 维修任务 Mapper
 *
 * @author zzy
 */
@Mapper
public interface RepairTaskMapper extends BaseMapperX<RepairTaskDO> {

    default PageResult<RepairTaskDO> selectPage(RepairTaskPageReqVO reqVO) {
        return selectPage(reqVO, new LambdaQueryWrapperX<RepairTaskDO>()
                .eqIfPresent(RepairTaskDO::getMaintenanceId, reqVO.getMaintenanceId())
                .eqIfPresent(RepairTaskDO::getEquipmentId, reqVO.getEquipmentId())
                .betweenIfPresent(RepairTaskDO::getCreateTime, reqVO.getCreateTime())
                .orderByDesc(RepairTaskDO::getId));
    }

    default PageResult<RepairTaskDO> selectMyPage(RepairTaskPageReqVO reqVO) {

        // 1. 计算精确总数（分组后的总记录数）
        Long total = this.selectCount(
                new QueryWrapper<RepairTaskDO>()
                        .select("DISTINCT equipment_id") // 原生 SQL 写 DISTINCT
        );

        if (total == 0) {
            return new PageResult<>(Collections.emptyList(), 0L);
        }

        // 2. 分页查询分组后的数据
        Page<Map<String, Object>> mpPage = new Page<>(reqVO.getPageNo(), reqVO.getPageSize());

        QueryWrapper<RepairTaskDO> wrapper = new QueryWrapper<>();
        wrapper.select(
                        "equipment_id",
                        "MAX(id) AS id", // 取该设备最新记录的ID
                        "MAX(repair_id) AS repair_id",
                        "MAX(maintenance_id) AS maintenance_id",
                        "MAX(start_time) AS start_time",
                        "MAX(end_time) AS end_time",
                        "SUM(repair_duration) AS repair_duration",
                        "SUM(repair_cost) AS repair_cost",
                        "MAX(resolved) AS resolved",
                        "MAX(fault_analysis) AS fault_analysis",
                        "MAX(repair_item) AS repair_item"
                )
                .eq(reqVO.getMaintenanceId() != null, "maintenance_id", reqVO.getMaintenanceId())
                .eq(reqVO.getEquipmentId() != null, "equipment_id", reqVO.getEquipmentId())
                .between(reqVO.getCreateTime() != null, "create_time",
                        reqVO.getCreateTime()[0], reqVO.getCreateTime()[1])
                .groupBy("equipment_id")
                .orderByDesc("MAX(id)");

        List<RepairTaskDO> records = this.selectMapsPage(mpPage, wrapper)
                .getRecords()
                .stream()
                .map(map -> {
                    RepairTaskDO dto = new RepairTaskDO();
                    dto.setId(((Number) map.get("id")).longValue());
                    dto.setRepairId(map.get("repair_id") != null ? ((Number) map.get("repair_id")).longValue() : null);
                    dto.setMaintenanceId(map.get("maintenance_id") != null ? ((Number) map.get("maintenance_id")).longValue() : null);
                    dto.setEquipmentId(map.get("equipment_id") != null ? ((Number) map.get("equipment_id")).longValue() : null);
                    dto.setStartTime((LocalDateTime) map.get("start_time"));
                    dto.setEndTime((LocalDateTime) map.get("end_time"));
                    dto.setRepairDuration(map.get("repair_duration") != null ? ((Number) map.get("repair_duration")).intValue() : null);
                    dto.setRepairCost((BigDecimal) map.get("repair_cost"));
                    dto.setResolved(map.get("resolved") != null ? ((Number) map.get("resolved")).intValue() : null);
                    dto.setFaultAnalysis((String) map.get("fault_analysis"));
                    dto.setRepairItem((String) map.get("repair_item"));
                    return dto;
                })
                .collect(Collectors.toList());

        // 3. 返回分页结果
        return new PageResult<>(records, total);
    }




}